package com.tian.jobhandler;

import com.tian.mapper.ChargeSystemMessageMapper;
import com.tian.util.ChargeMarketRedisKeyPrefix;
import com.tian.util.ConstantsUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RList;
import org.redisson.api.RMap;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Iterator;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-09 17:20
 * {@code @version:} 1.0
 */
@Slf4j
@Component
public class DeleteExpiredMessageJob {
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private ChargeSystemMessageMapper chargeSystemMessageMapper;


    @Transactional
    @XxlJob("deleteExpiredMessageJob")
    public void process() {
        RScoredSortedSet<String> scoredSortedSet = redissonClient.getScoredSortedSet(ChargeMarketRedisKeyPrefix.USER_SYSTEM_MESSAGE_SET_KEY);
        long currentTime = System.currentTimeMillis();
        // 使用迭代器逐步处理消息
        Iterator<String> iterator = scoredSortedSet.iterator();

        while (iterator.hasNext()) {
            String message = iterator.next();
            //存的时候按照 messageId:timestamp:userId
            String[] parts = message.split(ConstantsUtil.SET_MESSAGE_SPLIT);
            if (parts.length != 3) {
                log.error("Invalid message format: {}", message);
                scoredSortedSet.remove(message);
                continue;
            }
            long messageId = Long.parseLong(parts[0]); // messageId
            long expiredTime = Long.parseLong(parts[1]); // timestamp
            long userId = Long.parseLong(parts[2]); // userId
            //已超过三个月时间就删掉
            if (expiredTime <= currentTime) {
                chargeSystemMessageMapper.deleteByPrimaryKey(messageId);

                RList<Long> list = redissonClient.getList(ChargeMarketRedisKeyPrefix.USER_SYSTEM_MESSAGE_LIST_KEY + userId);
                list.remove(messageId);

                RMap<Long, String> map = redissonClient.getMap(ChargeMarketRedisKeyPrefix.USER_SYSTEM_MESSAGE_MAP_KEY + userId);
                map.remove(messageId);

                scoredSortedSet.remove(message);
            }
        }

    }
}
